<template>
  <view v-show="!isLoading" class="container">
    <!-- 商品图片轮播 -->
    <SlideImage
      v-if="!isLoading"
      :video="goods.video"
      :videoCover="goods.videoCover"
      :images="goods.images"
    />

    <!-- 商品信息 -->
    <view v-if="!isLoading" class="goods-info m-top20">
      <!-- 标题 -->
      <view class="goods-name flex-box">
        <text class="twoline-hide">{{ goods.name }}</text>
      </view>
      <!-- 促销价 -->
      <view class="price">
        <text class="priceName">促销价</text>
        <text class="priceText">￥{{ goods.price }}</text>
      </view>
      <!-- 原价 -->
      <view class="sale">
        <view class="showPrice">
          <text class="name">原价</text>
          <text class="text">￥{{ goods.showPrice }}</text>
        </view>
        <view class="saleText"> 销量 {{ goods.sale || 0 }} 件 </view>
      </view>
    </view>

    <!-- 选择商品规格 -->
    <view class="goods-choice">
      <view class="spec-list" v-if="isMore">
        <view class="specText">{{ name1 }}</view>
        <view
          @click="chose111(index)"
          :class="active == index ? 'specNname typeActive' : 'specNname'"
          v-for="(item, index) in list1"
          :key="index"
          >{{ item.value }}
        </view>
      </view>
      <view class="spec-list">
        <view class="specText">{{ name2 }}</view>
        <!-- @click="choose(v, i)" -->
        <view
          :class="v.active ? 'specNname typeActive' : 'specNname'"
          v-for="(v, i) in list2"
          :key="i"
          @click="chose222(i)"
        >
          <!-- {{ v.key }}: -->
          {{ v.value }}
        </view>
      </view>
      <view v-if="!isMore">
        <view class="spec-list">
          <view class="specText">{{ name1 }}</view>
          <view
            :class="active === i ? 'specNname typeActive' : 'specNname'"
            v-for="(v, i) in list1"
            @click="chose111(i)"
            :key="i"
          >
            {{ v.value }}
          </view>
        </view>
      </view>

      <view class="number">
        <text class="numberText">数量</text>
        <u-number-box
          min="1"
          max="20"
          button-size="20"
          bgColor="#FF0000"
          color="#ffffff"
          v-model="cartTotal"
        ></u-number-box>
      </view>
    </view>

    <!-- 商品服务 -->
    <Service v-if="!isLoading" :goods-id="productId" />

    <!-- 底部选项卡 -->
    <view class="footer-fixed">
      <view class="footer-container">
        <!-- 导航图标 -->
        <view class="foo-item-fast">
          <!-- 购物车 -->
          <!-- <view class="fast-item fast-item--cart" @click="onTargetCart"> -->
          <!-- <view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">
							{{ cartTotal > 99 ? '99+' : cartTotal }}
						</view>
						<view class="fast-icon">
							<u-icon name="shopping-cart" size="35"></u-icon>
						</view> -->

          <!-- </view> -->
        </view>
        <!-- 操作按钮 -->
        <view class="foo-item-btn">
          <view class="btn-wrapper">
            <view class="btn-item btn-item-deputy" @click="addCar">
              <text>加入购物车</text>
            </view>
            <view class="btn-item btn-item-main" @click="buy">
              <text>立即购买</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { productSearchDetail, addCar } from "@/api/goods";
import SlideImage from "./components/SlideImage";
import Service from "./components/Service";

export default {
  components: {
    SlideImage,
    Service,
  },
  data() {
    return {
      // 正在加载
      isLoading: true,
      // 当前商品ID
      productId: null,
      skuId: null, //商品类型ID
      name: "",
      // 商品详情
      goods: {
        price: 0, //促销价
        showPrice: 0, //原价
        sale: 0, // 销量
        images: [],
      },
      active: 0,
      // 购物车总数量
      cartTotal: 1,
      // 显示/隐藏SKU弹窗
      showSkuPopup: false,
      // 模式 1:都显示 2:只显示购物车 3:只显示立即购买
      skuMode: 1,
      specList: [],
      specification: {},
      carInfo: {
        img: "",
        price: 0,
      },
      carSpecification: {},
      carActive: 0,
      specifActive: null,
      carSpecifActive: null,
      productId: "",
      isMore: false,
      list1: [],
      list2: [],
      name1: "",
      name2: "",
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    uni.setNavigationBarTitle({ title: options?.name })
    uni.setStorageSync("detail1", "1");
    this.name = options.name;
    this.productId = options.productId;
    // 加载页面数据
    this.getGoodsDetail();
  },

  methods: {
    choose(v, i) {
      this.specification = this.specification.map((item, index) => {
        if (i === index) {
          item.specifActive = !item.specifActive;
        }
        return item;
      });
    },
    transformSpecificationData(originalData) {
      // 创建一个映射表用于按规格分组
      const specificationMap = new Map();

      // 遍历原始数据
      originalData.forEach((item) => {
        try {
          // 解析specification字段中的规格信息
          const specs = JSON.parse(item.specification);

          // 提取规格和品类信息
          const sizeSpec = specs[0];
          const categorySpec = specs[1];

          // 确保找到了必要的规格信息
          if (sizeSpec && categorySpec) {
            const sizeValue = sizeSpec.value;

            // 如果该规格还没有在映射表中，先创建它
            if (!specificationMap.has(sizeValue)) {
              specificationMap.set(sizeValue, {
                key: sizeSpec.key,
                value: sizeValue,
                child: [],
              });
            }

            // 创建子项，包含品类信息和原始数据的其他属性
            const childItem = {
              key: categorySpec.key,
              value: categorySpec.value,
              // 复制原始对象的其他属性
              ...item,
            };

            // 将子项添加到对应的规格组中
            specificationMap.get(sizeValue).child.push(childItem);
          }
        } catch (error) {
          console.error("处理数据项时出错:", error, "数据项:", item);
        }
      });

      // 将映射表转换为数组并返回
      return Array.from(specificationMap.values());
    },
    // 获取商品信息
    async getGoodsDetail() {
      this.isLoading = true;
      const res = await productSearchDetail({
        productId: this.productId,
      });
      this.specList = res;
      let c = 0;
      res.forEach((item, index) => {
        item.skuType = item.skuType || item.name;
        item.pic = item.pic
          ? (item.pic.startsWith('https')
            ? item.pic
            : 'https://saas.hzjhckj.com/api' + item.pic)
          : "https://building-d.oss-cn-hangzhou.aliyuncs.com/img/img.jpg";
        // if (item.choose == 1) {
        //   c = index;
        // }
      });
      this.list1 = [];
      if (res.length) {
        let x = JSON.parse(res[0].specification);
        this.isMore = x.length > 1;
        this.name1 = x[0].key;
        if (this.isMore) {
          this.name2 = x[1].key;
          this.list1 = this.transformSpecificationData(res);
        } else {
          this.name = JSON.parse(res[0].specification)[0].key;
          res.forEach((item) => {
            item.specification = JSON.parse(item.specification);
            this.list1.push({
              ...item,
              ...item.specification[0]
            })
          });
          console.log(999, this.list1);
        }
      }
      this.chose111(0);
      // this.typeClick(this.specList[c], c);
      this.isLoading = false;
    },
    chose111(index) {
      this.active = index
      console.log(9999, this.list1)
      if (this.isMore) {
        this.list2 = this.list1[index].child
        this.chose222(0);
      } else {
        this.chose333(this.list1[index]);
      }
    },
    chose222(index) {
      this.list2 = this.list2.map((item, i) => {
        item.active = index === i;
        return item;
      });
      this.chose333(this.list2[index]);
    },
    chose333(first) {
      this.goods = {
        price: first.price, //促销价
        showPrice: first.showPrice, //原价
        sale: first.sale, // 销量
        images: [
          {
            preview_url: first.pic,
          },
        ],
      };
      this.skuId = first.id;
      this.productId = first.productId;
    },
    typeClick(item, index) {
      this.goods = {
        price: item.price, //促销价
        showPrice: item.showPrice, //原价
        sale: item.sale, // 销量
        images: [
          {
            preview_url: item.pic,
          },
        ],
      };
      this.skuId = item.id;
      this.productId = item.productId;
      this.carInfo.img = item.pic;
      this.carInfo.price = item.price;
      this.carSpecification = JSON.parse(item.specification);
      this.carActive = index;
      this.specifActive = null;
      this.active = index;

      this.specification = JSON.parse(item.specification).map((item, index) => {
        item.specifActive = true; // index === 0 ? true : false
        return item;
      });
    },

    // 获取购物车总数量
    getCartTotal() {
      const app = this;
      return new Promise((resolve, reject) => {
        CartApi.total()
          .then((result) => {
            app.cartTotal = result.data.cartTotal;
            resolve(result);
          })
          .catch(reject);
      });
    },

    // 更新购物车数量
    onAddCart(total) {
      this.cartTotal = total;
    },

    /**
     * 显示/隐藏SKU弹窗
     * @param {skuMode} 模式 1:都显示 2:只显示购物车 3:只显示立即购买
     */
    onShowSkuPopup(skuMode) {
      this.skuMode = skuMode;
      this.showSkuPopup = true;
    },

    // 跳转到购物车页
    onTargetCart() {
      uni.switchTab({
        url: "/pages/shop/index",
      });
    },
    close() {
      this.showSkuPopup = false;
    },
    carTypeClick(index, item) {
      this.skuId = item.id;
      this.carActive = index;
      this.carSpecification = JSON.parse(item.specification);
    },
    specifClick(index) {
      this.carSpecifActive = index;
    },
    // 添加购物车
    async addCar() {
      const res = await addCar({
        skuId: this.skuId,
        productId: this.productId,
        num: this.cartTotal,
      });
      this.showSkuPopup = false;
      uni.showToast({
        title: "加入购物车成功",
      });
    },
    async buy() {
      this.showSkuPopup = false;
      uni.navigateTo({
        url: `/pages/checkout/index?cartIds=${this.skuId}&type=1`,
      });
    },
  },
};
</script>

<style>
page {
  background: #fafafa;
}
</style>
<style lang="scss" scoped>
@import "./detail.scss";
</style>
